from fastapi import FastAPI, Request, Depends
from src.router.api import api_router
import os
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.middleware.cors import CORSMiddleware  #引入 CORS中间件模块
from src.utils.user import my_oauth2_scheme
from src.views import ws
from src.utils.task_queue import start_queue, stop_queue
from src.utils.log import init_main_logger

root_path = os.path.dirname(os.path.abspath(__file__))

# ✅ 只在这里初始化一次主日志系统
init_main_logger()

app = FastAPI()

#设置允许访问的域名
origins = ["*"]  #也可以设置为"*"，即为所有。

#设置跨域传参
app.add_middleware(
    CORSMiddleware, 
    allow_origins=origins,  #设置允许的origins来源
    allow_credentials=True,
    allow_methods=["*"],  # 设置允许跨域的http方法，比如 get、post、put等。
    allow_headers=["*"])  #允许跨域的headers，可以用来鉴别来源等作用。


app.mount("/static", StaticFiles(directory="dist/static"), name="static")

templates = Jinja2Templates(directory="dist")

# 在需要认证的路由中显式使用 Depends(my_oauth2_scheme)
app.include_router(api_router, prefix="/api", dependencies=[Depends(my_oauth2_scheme)])
app.include_router(ws.router, prefix="/ws", dependencies=[])

@app.on_event("startup")
async def startup():
    start_queue()

@app.on_event("shutdown")
async def shutdown():
    stop_queue()

@app.get('/', response_class=HTMLResponse)
def index(request: Request):
    return templates.TemplateResponse('index.html', {"request": request})
